﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

using Microsoft.Xna.Framework.Graphics;

namespace Daybreak.Core
{
    public partial class Scene
    {
        /// <summary>
        /// Declares the storage for the graphical representation of an object
        /// </summary>
        public class Image
        {
            public string Name;

            /// <summary>
            /// Specifies an external image file. 
            /// </summary>
            public string File;

            /// <summary>
            /// Ready to render texture object
            /// </summary>
            public Texture Texture;

            public Image(string file)
            {
                this.File = file;
            }

            public void Load(ImageLib lib)
            {
                if (Texture == null)
                    Texture = Engine.LoadTexture(lib, File);
            }
        }

        /// <summary>
        /// Declares a module of Image objects
        /// </summary>
        public class ImageLib
        {
            public List<Image> ImageList = new List<Image>();
            public bool Loaded;

            public ImageLib()
            {
            }

            public Image AddImage(string name, string file)
            {
                Image img = new Image(file);
                img.Name = name;
                ImageList.Add(img);

                return img;
            }

            public void Load(bool deferred)
            {
                if (!deferred)
                {
                    LoadTextures();

                    return;
                }

                Thread thread = new Thread(new ThreadStart(LoadTextures));
                thread.IsBackground = true;
                thread.Priority = ThreadPriority.BelowNormal;
                thread.Start();

            }

            private void LoadTextures()
            {
                for (int i = 0; i < ImageList.Count; i++)
                    ImageList[i].Load(this);

                Loaded = true;
            }

            public Image FindByName(string name)
            {
                for (int i = 0; i < ImageList.Count; i++)
                    if (ImageList[i].Name == name)
                        return ImageList[i];

                return null;

            }

            public Image FindByFile(string fileName, bool create)
            {
                for (int i = 0; i < ImageList.Count; i++)
                    if (ImageList[i].File == fileName)
                        return ImageList[i];

                return AddImage(Path.GetFileName(fileName), fileName);
            }
        }


    }
}
